const express = require("express");
const { db } = require("../database");

const { validate, validators } = require("../validate");

const { makePassword } = require("../utils");
const {useAuthorization} = require("./base")

// 创建路由对象，使得用户登录状态检查的中间件只作用于部分路由。
const router = express.Router();
// 创建用户登录状态检查的中间件
router.use(useAuthorization);

router
  /**
   * 用户注销
   */
  .get("/logout", (req, res) => {
    // 清除 session 信息
    req.session.destroy();
    res.send({
      success: true,
      message: "用户注销成功！",
    });
  })
  /**
   * 获取用户信息
   */
  .get("/user/info", async (req, res) => {
    res.send({
      success: true,
      user: req.user,
    });
  })
  /**
   * 新建待办
   */
  .post(
    "/todos",
    validate(validators.title, validators.description, validators.priority),
    async (req, res) => {
      const { title, description, priority } = req.body;
      const id = await db.insert(
        "insert into todo (title, description, priority, user_id) values (?, ?, ?, ?)",
        [title, description, priority, req.session.userId]
      );
      const todo = await db.findOne`select * from todo where id = ${id}`;
      res.send({
        success: true,
        object: todo,
      });
    }
  )
  /**
   * 修改待办信息
   */
  .put(
    "/todos/:tid",
    validate(
      validators.title,
      validators.description,
      validators.priority,
      validators.todoId
    ),
    async (req, res) => {
      console.log("->", req.user.id);
      let todo =
        await db.findOne`select * from todo where id = ${req.params.tid} and user_id = ${req.user.id}`;
      if (!todo) {
        return res.send({ success: false, message: "该待办信息不存在！" });
      }
      if (todo.finished_at) {
        return res.send({
          success: false,
          message: "该待办已经完成，不能修改！",
        });
      }
      const { title, description, priority } = req.body;
      await db.run`update todo set title = ${title}, description = ${description}, priority = ${priority} where id = ${req.params.tid}`;
      todo = await db.findOne`select * from todo where id = ${req.params.tid}`;
      res.send({ success: true, object: todo });
    }
  )
  .delete("/todos/:tid", validate(validators.todoId), async (req, res) => {
    const todo =
      await db.findOne`select * from todo where id = ${req.params.tid} and user_id = ${req.user.id}`;
    if (!todo) {
      return res.send({ success: false, message: "该待办信息不存在！" });
    }
    // 删除 todo 记录
    await db.run`delete from todo where id = ${req.params.tid}`;
    res.send({
      success: true,
      message: "删除成功",
    });
  })
  .put("/todos/finish/:tid", validate(validators.todoId), async (req, res) => {
    let todo =
      await db.findOne`select * from todo where id = ${req.params.tid} and user_id = ${req.user.id}`;
    if (!todo) {
      return res.send({ success: false, message: "该待办信息不存在！" });
    }
    if (todo.finished_at) {
      return res.send({
        success: false,
        message: "该待办信息已经完成，不需再次完成！",
      });
    }
    await db.run(
      "update todo set finished_at = current_timestamp where id = ?",
      [req.params.tid]
    );
    todo = await db.findOne("select * from todo where id = ?", [
      req.params.tid,
    ]);
    res.send({
      success: true,
      object: todo,
    });
  })
  .get(
    "/todos",
    validate(validators.limit, validators.offset),
    async (req, res) => {
      const {
        days = "all",
        priority = "all",
        isFinished = "all",
        limit = 10,
        offset = 0,
      } = req.query;
      const wheres = ["user_id = ?"],
        params = [req.user.id];
      if (days != "all") {
        wheres.push(
          db.engine == "mysql"
            ? `created_at between date_add(now(), interval - ${days} day) and now()`
            : `created_at between date('now', '-${days} day') and datetime('now')`
        );
      }
      if (priority != "all") {
        wheres.push("priority = ?");
        params.push(priority);
      }
      if (isFinished != "all") {
        wheres.push(`finished_at is ${isFinished == "true" ? "not" : ""} null`);
      }
      // 获取查询的总数
      let sql = `select count(*) as count from todo where ${wheres.join(
        " and "
      )}`;
      const { count } = await db.findOne(sql, params);
      // 执行查询 sql
      sql = `select * from todo where ${wheres.join(
        " and "
      )} order by created_at desc limit ${offset}, ${limit}`;
      const results = await db.select(sql, params);
      res.send({
        success: true,
        query: {
          count,
          limit,
          offset,
          page: offset / limit + 1,
          results,
        },
      });
    }
  )
  .get("/todos/stat", async (req, res) => {
    const { id } = req.user,
      { count } = await db.findOne(
        "select count(*) as count from todo where user_id = ?",
        [id]
      ),
      finished = await db.select(
        `select priority, count(*) as count from todo 
          where user_id = ? and finished_at is not null
          group by priority`,
        [id]
      ),
      notFinished = await db.select(
        `select priority, count(*) as count from todo
          where user_id = ? and finished_at is null
          group by priority`,
        [id]
      );
    res.send({
      success: true,
      stat: {
        count,
        finished,
        notFinished,
      },
    });
  })
  // .put(
  //   "/user/changePassword",
  //   validate(
  //     validators.oldPassword,
  //     validators.password,
  //     validators.confirmPassword
  //   ),
  //   async (req, res) => {
  //     const { oldPassword, password } = req.body;
  //     if (!checkPassword(oldPassword, req.user.password)) {
  //       return res.send({
  //         success: false,
  //         message: "原密码不正确，不能执行修改密码操作！",
  //       });
  //     }
  //     if (oldPassword == password) {
  //       return res.send({
  //         success: false,
  //         message: "新密码和原密码不能相同！",
  //       });
  //     }
  //     await db.run("update user set password = ? where id = ?", [
  //       makePassword(password),
  //       req.user.id,
  //     ]);
  //     res.send({
  //       success: true,
  //       message: "密码修改成功！",
  //     });
  //   }
  // );

// 将路由作为中间件挂接在 / 根路由上。
const registerRouter = (app) => app.use("/", router);

module.exports = { registerRouter };
